package com.net.wanjian.networkhospitalmanager.fragment.skilltrain;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;

import com.net.wanjian.networkhospitalmanager.R;
import com.net.wanjian.networkhospitalmanager.activity.skilltrain.LabDetailsActivity;
import com.net.wanjian.networkhospitalmanager.adapter.LabReserveListAdapter;
import com.net.wanjian.networkhospitalmanager.adapter.base.RecyclerBaseAdapter;
import com.net.wanjian.networkhospitalmanager.bean.LabReserveListReturn;
import com.net.wanjian.networkhospitalmanager.consts.AppConsts;
import com.net.wanjian.networkhospitalmanager.consts.ErrorCodeReturn;
import com.net.wanjian.networkhospitalmanager.fragment.base.BaseFragment;
import com.net.wanjian.networkhospitalmanager.net.HttpUtil;
import com.net.wanjian.networkhospitalmanager.netstatus.NetUtils;
import com.net.wanjian.networkhospitalmanager.utils.SharedXmlUtil;
import com.net.wanjian.networkhospitalmanager.utils.URLDecoderUtil;
import com.net.wanjian.networkhospitalmanager.view.NoDataEmptyView;
import com.net.wanjian.networkhospitalmanager.widge.RefreshRecyclerView;

import java.util.List;

import butterknife.BindView;
import io.reactivex.observers.DisposableObserver;

/**
 * Description:实验室预约
 * Created by lidongcai on 2017/4/26.
 * Email:  lidongcaiocc@163.com
 */
public class LaboratoryReservationFragment extends BaseFragment {

    @BindView(R.id.laboratory_recycler_view)
    RefreshRecyclerView laboratoryRecyclerView;
    @BindView(R.id.no_data_layout)
    NoDataEmptyView noDataLayout;
    @BindView(R.id.fragment_laboratory_progress)
    ProgressBar mProgressBar;

    private LabReserveListAdapter listAdapter;
    private List<LabReserveListReturn.DataBean.LabReserveListBean> labReserveList;
    private int currentNum = AppConsts.currentPageNum, currentPageNum, countNum;

    private LocalBroadcastManager localBroadcastManager;

    @Override
    public void onResume() {
        super.onResume();
    }

    //获取预约实验列表,老师和学生一样
    public void getLabreserveHttpRequest() {
        currentPageNum = 0;
        SharedXmlUtil xmlUtil = SharedXmlUtil.getInstance();
        HttpUtil.getLabreserveList(xmlUtil.getDeviceId(), xmlUtil.getToken(), xmlUtil.getHospitalId(), xmlUtil.getUserIdentityId(),
                xmlUtil.getUserIdentity(), currentPageNum, currentNum, new DisposableObserver<LabReserveListReturn>() {
                    @Override
                    public void onNext(LabReserveListReturn labReserveListReturn) {
                        if (labReserveListReturn.getResult() == ErrorCodeReturn.success) {
                            countNum = Integer.parseInt(labReserveListReturn.getData().getTotalCount());
                            SharedXmlUtil.getInstance().setToken(URLDecoderUtil.getDecoder(labReserveListReturn.getData().getToken()));

                            Log.e(TAG, "onNext: " + "labReserveListReturn");
                            labReserveList = labReserveListReturn.getData().getLabReserveList();

                            initRecyclerList();

                            if (labReserveListReturn.getData().getLabReserveList().size() < currentNum || labReserveList.size() >= countNum) {
                                laboratoryRecyclerView.refreshComplete();
                                laboratoryRecyclerView.setNoMore(true);
                            }else {
                                laboratoryRecyclerView.refreshComplete();
                                laboratoryRecyclerView.setNoMore(false);
                            }
                        }else {
                            laboratoryRecyclerView.refreshComplete();
                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                        laboratoryRecyclerView.refreshComplete();
                    }

                    @Override
                    public void onComplete() {
                    }
                });

    }

    private void initRecyclerList() {
            mProgressBar.setVisibility(View.GONE);
            listAdapter = new LabReserveListAdapter(mContext);
            listAdapter.setList(labReserveList);
            laboratoryRecyclerView.setAdapter(listAdapter);

        listAdapter.setOnItemClickListener(new RecyclerBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int pos) {
                Bundle bundle = new Bundle();
                bundle.putString(LabDetailsActivity.LAB_RESERVE_ID_KEY, URLDecoderUtil.getDecoder(labReserveList.get(pos).getLabReserveID()));
                bundle.putSerializable(LabDetailsActivity.LAB_RESERVE_DATA_KEY, labReserveList.get(pos));
                bundle.putInt(LabDetailsActivity.LAB_RESERVE_TYPE_KEY, 0);
                openActivity(LabDetailsActivity.class, bundle);
            }
        });
    }

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ("refreshlabreserve".equals(intent.getAction())) {
                laboratoryRecyclerView.refresh();
            }
        }
    };

    @Override
    protected void initView() {
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        IntentFilter filter = new IntentFilter();
        filter.addAction("refreshlabreserve");
        localBroadcastManager.registerReceiver(receiver, filter);

        noDataLayout.setNoData(R.string.no_lab_text);
        noDataLayout.setOnReLoadClickListener(new NoDataEmptyView.OnReLoadClickListener() {
            @Override
            public void onReloadClick(View v) {
                getLabreserveHttpRequest();
            }
        });
        laboratoryRecyclerView.setEmptyView(noDataLayout);
        laboratoryRecyclerView.setRefreshMode(3);
        laboratoryRecyclerView.addOnRefreshListener(new RefreshRecyclerView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getLabreserveHttpRequest();
            }

            @Override
            public void onLoadMore() {
                loadMore();
            }
        });
        laboratoryRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        laboratoryRecyclerView.refresh();
    }

    //加载更多
    private void loadMore() {
        currentPageNum++;
        Log.e(TAG, "loadMore: " + currentPageNum + "到多少页" + currentNum + "共" + countNum);
        SharedXmlUtil xmlUtil = SharedXmlUtil.getInstance();
        HttpUtil.getLabreserveList(xmlUtil.getDeviceId(), xmlUtil.getToken(), xmlUtil.getHospitalId(), xmlUtil.getUserIdentityId(),
                xmlUtil.getUserIdentity(), currentPageNum, currentNum, new DisposableObserver<LabReserveListReturn>() {
                    @Override
                    public void onNext(LabReserveListReturn labReserveListReturn) {
                        if (labReserveListReturn.getResult() == ErrorCodeReturn.success) {
                            SharedXmlUtil.getInstance().setToken(URLDecoderUtil.getDecoder(labReserveListReturn.getData().getToken()));
                            List<LabReserveListReturn.DataBean.LabReserveListBean> reserveList = labReserveListReturn.getData().getLabReserveList();
                            labReserveList.addAll(reserveList);
                            listAdapter.setList(LaboratoryReservationFragment.this.labReserveList);
                            Log.e(TAG, "onNext: " + reserveList.size());
                            if (reserveList.size() < currentNum || labReserveList.size() >= countNum) {
                                laboratoryRecyclerView.setNoMore(true);

                            } else {
                                laboratoryRecyclerView.loadMoreComplete();
                            }

                        } else {
                            laboratoryRecyclerView.loadMoreComplete();

                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                        laboratoryRecyclerView.loadMoreComplete();
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {
        noDataLayout.setNoData(R.string.no_lab_text);
        laboratoryRecyclerView.setEmptyView(noDataLayout);
        getLabreserveHttpRequest();
    }

    @Override
    protected void onNetworkDisConnected() {
        labReserveList = null;

        noDataLayout.setNoNetWork();
        laboratoryRecyclerView.setEmptyView(noDataLayout);
        listAdapter.notifyDataSetChanged();
    }

    public static LaboratoryReservationFragment getInstance() {
        LaboratoryReservationFragment fragment = new LaboratoryReservationFragment();
        return fragment;
    }

    @Override
    public void onDestroy() {
        localBroadcastManager.unregisterReceiver(receiver);
        super.onDestroy();
    }

    @Override
    protected void initData() {
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_laboratory_reservation;
    }

}
